<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { Apis } from '#/api';
import { Page } from '#/components/page';

import EditRoleModal, {
  type EditRoleModalState,
} from './components/edit-role-modal.vue';

const [BaseEditRoleModal, baseEditRoleModalApi] = useVbenModal({
  connectedComponent: EditRoleModal,
});

const gridRef = ref<any>(null);

interface RowType {
  category: string;
  color: string;
  id: string;
  price: string;
  productName: string;
  releaseDate: string;
}

const formOptions: VbenFormProps = {
  collapsed: false,
  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      label: '角色名称',
    },
    {
      component: 'Input',
      fieldName: 'code',
      label: '角色编码',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '正常',
            value: '1',
          },
          {
            label: '封禁',
            value: '2',
          },
        ],
        placeholder: '请选择',
      },
      fieldName: 'status',
      label: '记录状态',
    },
  ],
  showCollapseButton: true,
  submitOnEnter: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-4',
};

const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: '',
  },
  scrollX: {
    enabled: true,
  },
  scrollY: {
    enabled: true,
  },
  columns: [
    { type: 'checkbox', width: 50 },
    { title: '序号', type: 'seq', width: 50 },
    {
      field: 'name',
      title: '角色名称',
      treeNode: true,
      width: 200,
    },
    { field: 'code', title: '角色编码', width: 150 },
    { field: 'status', title: '记录状态', width: 100 },
    { field: 'remark', title: '备注', minWidth: 160 },
    {
      field: 'createdAt',
      title: '创建时间',
      width: 150,
      sortable: true,
      sortType: 'string',
    },
    {
      field: 'updatedAt',
      title: '修改时间',
      width: 150,
      sortable: true,
      sortType: 'string',
    },
    {
      field: 'action',
      title: '操作',
      width: 260,
      fixed: 'right',
      align: 'center',
      slots: { default: 'action' },
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    enabled: false,
  },
  rowConfig: {
    isCurrent: true,
  },
  proxyConfig: {
    ajax: {
      query: async (_, formValues) => {
        const data = await Apis.system.role.getList({
          params: {
            ...formValues,
          },
        });
        data.list.forEach((item) => {
          if (item.code !== 'merchantManager') {
            item.parentId = '11';
          }
        });
        return data;
      },
    },
  },
  treeConfig: {
    transform: true,
    parentField: 'parentId',
    rowField: 'id',
  },
};

const selectedRows = ref<any[]>([]);

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    cellClick({ row }) {
      gridApi.grid.toggleCheckboxRow(row);
      selectedRows.value = gridApi.grid.getCheckboxRecords();
    },
    checkboxChange() {
      selectedRows.value = gridApi.grid.getCheckboxRecords();
    },
    checkboxAll() {
      selectedRows.value = gridApi.grid.getCheckboxRecords();
    },
  },
});

function handleEdit(row?: any) {
  baseEditRoleModalApi.setData<EditRoleModalState>({
    isUpdate: !!row,
    record: row || {},
  });
  baseEditRoleModalApi.open();
}

function handleDelete(rows: any[]) {
  if (rows.length === 0) {
    message.error('请选择要删除的记录');
    return;
  }
  Modal.confirm({
    title: '确定要删除吗？',
    content: '删除后将无法恢复',
    onOk: () => {
      if (rows.length === 1) {
        message.error('请选择单个记录进行删除');
        return;
      }
      return rows;
    },
  });
}
</script>

<template>
  <Page content-class="h-full flex flex-col">
    <BaseEditRoleModal />
    <Grid ref="gridRef" table-title="角色列表">
      <template #toolbar-tools>
        <a-space>
          <a-button type="primary" @click="handleEdit()">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
          <a-button
            :disabled="selectedRows.length === 0"
            danger
            type="primary"
            @click="handleDelete(selectedRows)"
          >
            <template #icon>
              <DeleteOutlined />
            </template>
            批量删除
          </a-button>
        </a-space>
      </template>

      <template #isDeleted="{ row }">
        <a-tag :color="row.deletedAt ? 'red' : 'green'">
          {{ row.deletedAt ? '已删除' : '未删除' }}
        </a-tag>
      </template>
      <template #action="{ row }">
        <a-button size="small" type="link" @click.stop="handleEdit(row)">
          权限分配
        </a-button>
        <a-button size="small" type="link" @click.stop="handleEdit(row)">
          添加下级
        </a-button>
        <a-button size="small" type="link" @click.stop="handleEdit(row)">
          编辑
        </a-button>
        <a-button
          danger
          size="small"
          type="link"
          @click.stop="handleDelete([row])"
        >
          删除
        </a-button>
      </template>
    </Grid>
  </Page>
</template>
